<?php
namespace App\Model\Product;

use App\Model\Config;
use Jenssegers\Mongodb\Eloquent\Model;
use App\Common\Product as Contract;

class Product extends Model
{
    use \App\Plugin\Debuger;
    use \App\Common\Eloquent\Model\Cache;
    use \App\Services\MongoAI\Inc;
    use \App\Common\Config;


    public function __construct(array $attributes = [])
    {
        $this->connection = self::mongoConn();
        parent::__construct($attributes);

    }

    protected static function boot()
    {
        parent::boot();
        static::saving(function ($model) {
            $model->init();
        });

    }



//	protected $connection = '';
    protected $table = 'product';



    protected $primaryKey = 'mfn';
    public $timestamps = false;

    protected $fillable = [
        'mfn' => 'mfn',
        'name' => 'name', // 品名
        'cat' => 'cat', // 品类
        'mat' => 'mat', // 主材质
        'clr' => 'clr', // 主色
        'length' => 'length',
        'width' => 'width',
        'height' => 'height',
        'weight' => 'weight',
//		'cover' => 'cover',
        'album' => 'album',
    ];


    protected $guarded = [
        'id'
    ];


    /**
     * 是否新创建
     * @return bool
     * */
    public function isNew ():bool
    {
        return $this->_id ? (bool)self::debug('已存在商品MFN不可更改。') : true;
    }


    /**
     * 初始化 生成ID和MFN
     * */
    public function init ()
    {
        if ($this->isNew()) {
            $this->attributes['id'] = self::ai();
            $this->attributes['mfn'] = $this->makeFfn(trim(@$this->attributes['mfn']));
            $this->attributes['datetime'] = date('Y-m-d H:i:s');
        }
        return $this;
    }




    protected static $mfn = null;

    /**
     * 生成MFN
     * @param $mfn string
     * @return string
     * */
    public function makeFfn ($mfn='')
    {
        self::$mfn = self::$mfn ?: new Contract\MFN;
        $obj =& self::$mfn;
        if (!$mfn) {
            $obj->set($mfn, $obj->year())
                ->set($mfn, $obj->month())
                ->set($mfn, '-')
                ->set($mfn, @$this->cat)
                ->set($mfn, @$this->clr)
                ->set($mfn, @$this->mat)
                ->set($mfn, $obj->length(@$this->length))
                ->set($mfn, $obj->length(@$this->height));
        }
        return $obj->check($mfn);
    }




    /**
     * 检测数据是否合法
     * @return bool
     * */
    public function isValid ():bool
    {
        if (!$this->name) {
            return (bool)self::debug('品名不可为空。');
        }

        return true;
    }




    /**
     * 查找商品ID并自动缓存
     * @param $id int|array
     * @return object|null
     * */
    static function findIdWithCache ($id)
    {
        return self::findWithCache($id, 'id');
    }

}